<template>
  <el-card>
    <el-tabs v-model="activeName" :style="{height:tableHeight+'px'}">
      <el-tab-pane label="字段信息" name="columnInfo">
        <el-alert
          title="拖拽序号，可调整字段位置"
          type="success"
          :closable="false">
        </el-alert>
        <div class="columnInfo-box">
          <el-table ref="dragTable"
                    class="column-table" :data="columns" row-key="columnId" :max-height="(tableHeight-100)+'px'"
                    fit
                    highlight-current-row
                    @current-change="columnTableCurrentChange"
          >
            <el-table-column label="序号" type="index" min-width="20px" class-name="allowDrag" />
            <el-table-column
              label="字段列名"
              prop="columnName"
              min-width="50px"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <span class="copy-column" @click="handCopyData(scope.row.columnName)">{{ scope.row.columnName }}</span>
              </template>
            </el-table-column>

            <el-table-column
              label="Java属性名"
              prop="javaField"
              min-width="50px"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <span class="copy-column" @click="handCopyData(scope.row.javaField)">{{ scope.row.javaField }}</span>
              </template>
            </el-table-column>

            <el-table-column label="字段类型" min-width="60px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.columnType"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="中文字段名" min-width="100px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.columnComment"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="描述" min-width="150px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.columnDesc"></el-input>
              </template>
            </el-table-column>
          </el-table>
          <div class="column-config">
<!--            <div class="title">属性配置</div>-->
            <el-form class="column-form" size="small" label-width="90px" v-if="nowColumnTableRow!=null"
                     :style="{height:(tableHeight-100)+'px'}">
              <el-form-item label="组件类型">
                <el-select v-model="nowColumnTableRow.htmlType">
                  <el-option label="文本框" value="input" />
                  <el-option label="搜索文本框" value="searchInput" />
                  <el-option label="文本域" value="textarea" />
                  <el-option label="数字类型" value="number" />
                  <el-option label="下拉框" value="select" />
                  <el-option label="多选下拉框" value="multipleSelect" />
                  <el-option label="单选框" value="radio" />
                  <el-option label="复选框" value="checkbox" />
                  <el-option label="日期控件" value="date"/>
                  <el-option label="日期时间控件" value="datetime" />
                  <el-option label="富文本控件" value="tinymce" />
                  <el-option label="计数器" value="inputNumber" />
                </el-select>
              </el-form-item>

              <el-form-item label="字典类型" v-if="nowColumnTableRow.htmlType=='select' || nowColumnTableRow.htmlType=='multipleSelect' || nowColumnTableRow.htmlType=='radio'  || nowColumnTableRow.htmlType=='checkbox'">
                <el-select v-model="nowColumnTableRow.dictType" clearable filterable placeholder="请选择">
                  <el-option
                    v-for="dict in dictOptions"
                    :key="dict.dictType"
                    :label="dict.dictName"
                    :value="dict.dictType">
                    <span style="float: left">{{ dict.dictName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictType }}</span>
                  </el-option>
                </el-select>
              </el-form-item>

              <!-------------------------------查询配置------------------------------- -->
              <el-divider class="config-divider">查询配置</el-divider>
              <el-form-item label="查询">
                <el-checkbox true-label="1" false-label="0" v-model="nowColumnTableRow.isQuery">数据查询区域，是否展示</el-checkbox>
              </el-form-item>
              <el-form-item label="查询方式">
                <el-select v-model="nowColumnTableRow.queryType">
                  <el-option label="等于" value="EQ" />
                  <el-option label="包含" value="LIKE" />
                </el-select>
              </el-form-item>

              <!-------------------------------列表展示------------------------------- -->
              <el-divider class="config-divider">列表展示</el-divider>
              <el-form-item label="列表展示">
                <el-checkbox true-label="1" false-label="0" v-model="nowColumnTableRow.isList">数据列表中是否展示</el-checkbox>
              </el-form-item>
              <el-form-item label="列表宽度">
                <el-input v-model="nowColumnTableRow.columnWidth"></el-input>
              </el-form-item>
              <el-form-item label="对齐方式">
                <el-select v-model="nowColumnTableRow.columnAlign">
                  <el-option label="居左" value="left" />
                  <el-option label="居中" value="center" />
                  <el-option label="居右" value="right" />
                </el-select>
              </el-form-item>

              <el-form-item label="列表排序">
                <el-checkbox true-label="1" false-label="0" v-model="nowColumnTableRow.isAllowSort">对表格数据进行排序</el-checkbox>
              </el-form-item>

              <el-form-item>
                <span slot="label">
                  固定展示
                  <el-tooltip content="固定展示在Table列表中，不会随滚动条移动" placement="left">
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </span>
                <el-checkbox true-label="true" false-label="false" v-model="isFixedColumn" @change="handIsFixedColumn">固定展示在Table列表中</el-checkbox>
              </el-form-item>
              <el-form-item v-if="parseBoolVal(isFixedColumn)">
                <span slot="label">
                  固定位置
                  <el-tooltip content="固定在列表的左边，还是右边" placement="left">
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </span>
                <el-radio-group v-model="nowColumnTableRow.fixed">
                  <el-radio-button label="left">左边</el-radio-button>
                  <el-radio-button label="right">右边</el-radio-button>
                </el-radio-group>
              </el-form-item>

            </el-form>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="表格样式" name="tableInfo">
        <div class="tableInfo-box">
          <div class="table-box">
            <component v-if="tableComponentIsValid"
                       :is="tableComponent"
                       :data="tableDemoData"
                       :tableConfig="tableConfig"/>
          </div>
          <div class="table-style-config">
            <el-form class="column-form" size="small" label-width="90px" v-if="tableConfig!=null"
                     :style="{height:(tableHeight-100)+'px'}">
              <el-form-item>
                <span slot="label">
                  表格样式
                  <el-tooltip content="自定义路径：/views/youshuda/components/FormBuild/component/cn/youshuda/table" placement="left">
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </span>
                <el-select v-model="tableConfig.moduleType" @change="handChangeTableModuleType">
                  <el-option v-for="(item,index) in tableComponents" :key="index" :label="item.label" :value="item.moduleType" />
                </el-select>
              </el-form-item>

              <el-divider class="config-divider">表格配置</el-divider>
              <component v-if="tableConfigComponentIsValid"
                         :is="tableConfigComponent"
                         :tableConfig="tableConfig"
                         :columns="columns"
                         :demoData="demoData"
                         @setTableDemoData="setTableDemoData"/>
            </el-form>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<script>

import Sortable from "sortablejs";
import request from "@/utils/request";
import {DynTableMixins} from "@/views/youshuda/components/FormBuild/component/cn/youshuda/pc/table/mixin/DynTableMixins";

export default {
  name: "TableColumnInfo",
  mixins:[DynTableMixins],
  components: {
  },
  props:{
    //表单设计唯一key
    formBuildKey: {
      type: String,
      default: null
    },
    tables:{
      type:Array,
      default:()=>[]
    },
    columns:{
      type:Array,
      default:()=>[]
    },
    dictOptions:{
      type:Array,
      default:()=>[]
    }
  },
  computed:{
    tableConfigInfo(){
      if(this.tableConfig){
        let _tableConfig = {...this.tableConfig}
        Object.keys(this.tableConfigTemp).forEach(key=>{
          delete _tableConfig[key]
        })
        return _tableConfig;
      }
      return null
    }
  },
  data() {
    return {
      // 选中选项卡的 name
      activeName: "columnInfo",
      // 表格的高度
      tableHeight: document.documentElement.scrollHeight - 300,
      // 字段表格当前点击的行信息
      nowColumnTableRow: null,
      // 数据表格组件
      tableComponents: [],
      // 数据表格信息
      tableConfig: {},
      tableConfigTemp: {
        //表格的ref
        ref: 'tables',
        // 遮罩层
        loading: false,
        //表格高度
        tabHeight: document.documentElement.scrollHeight - 430,
        //表格字段信息
        tableColumnInfo: [],
        //表格操作按钮信息
        tableBtns: [{label:'确 定',type:'warning'},{label:'取 消'}],
        /** 列表按钮区宽度 */
        tableBtnsBoxWidth:200,
        // 总条数
        total: 0
      },
      //表格Demo数据
      demoData:null,
      tableDemoData:null,
      isFixedBtnColumn:false,
      isFixedColumn:false
    };
  },
  created() {
    // 数据表格组件
    this.tableComponents = this.$store.state.component.tableComponents
  },
  mounted() {
    const el = this.$refs.dragTable.$el.querySelectorAll(".el-table__body-wrapper > table > tbody")[0];
    const sortable = Sortable.create(el, {
      handle: ".allowDrag",
      onEnd: evt => {
        const targetRow = this.columns.splice(evt.oldIndex, 1)[0];
        this.columns.splice(evt.newIndex, 0, targetRow);
        for (let index in this.columns) {
          this.columns[index].sort = parseInt(index) + 1;
        }
        // if(this.$refs.dragTable && this.columns && this.columns.length>0){
        //   this.$refs.dragTable.setCurrentRow(this.columns[0]);
        // }
      }
    });
  },
  methods: {
    /** 复制内容到剪切板 **/
    handCopyData(data){
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(data).then(()=>{
          this.msgSuccess('成功复制【'+data+'】')
        }).catch(err=>{
          this.msgError('复制失败，请开启浏览器剪切板权限')
        })
      } else {
        const input = document.createElement('input');
        input.value = data;
        document.body.appendChild(input);
        input.select(); // 选取文本域中的内容.
        let bool = document.execCommand('Copy'); // 不支持copy方法返回false，支持返回true
        if(bool){
          this.msgSuccess('成功复制【'+data+'】')
        }else{
          this.msgError('复制失败，请开启浏览器剪切板权限')
        }
        document.body.removeChild(input);	// 必需是在复制语句之后移除
      }

    },
    /** 字段表格当前点击的行信息 **/
    columnTableCurrentChange(row){
      this.isFixedColumn = true
      if(this.isEmpty(row['fixed']) || row['fixed'] ==false || row['fixed'] == 'false'){
        row['fixed'] = false
        this.isFixedColumn = false
      }
      this.nowColumnTableRow=row
    },
    assTableConfig(){
      /** 记录列表字段信息 **/
      if(this.columns){
        let demoData={}
        let tableColumnInfo = this.columns.filter((column, index, self) => {
          if(column.isList == '1'){
            demoData[column.columnName] = column.columnComment
            return true
          }
          return false
        })
        this.demoData=demoData
        this.$set(this.tableConfigTemp,'tableColumnInfo',tableColumnInfo)
      }
    },
    /**固定列字段**/
    handIsFixedColumn(obj){
      let fixed = 'left'
      if(obj == false || obj == 'false'){
        fixed = false
      }
      Object.assign(this.nowColumnTableRow,{fixed:fixed})
    },
    /** 处理数据为bool类型 **/
    parseBoolVal(val){
      if (val === true || String(val).toLowerCase() === 'true') {
        return true
      }
      return false
    },
    /** 获取数据表配置 */
    getCrudTableConfig(){
      if (!this.isNotEmpty(this.formBuildKey)) {
        this.$message.error('表单模块标识不能为空')
        return
      }
      request({
        url: 'form/crud/tabConfig/'+this.formBuildKey,
        method: 'get'
      }).then(res=>{
        if(res.code!=200){
          this.msgError(res.msg)
          return;
        }
        /** 数据表格样式切换 **/
        if(res.data){
          this.changeTableTarget(res.data);
        }else{
          this.handChangeTableModuleType('Default');
        }
      })
    },
    /** 数据表格样式切换 **/
    handChangeTableModuleType(moduleType){
      let target = this.tableComponents.find(item => item.moduleType === moduleType)
      /** 数据表格样式切换 **/
      this.changeTableTarget(target);
    },
    /** 数据表格样式切换 **/
    changeTableTarget(moduleConfig){
      let tableModuleType = 'Default'
      if(moduleConfig){
        tableModuleType=moduleConfig['moduleType']
        this.tableConfig={...this.tableConfigTemp,...moduleConfig}
      }
      /**
       * 加载数据表格
       */
      this.loadTableComponent(tableModuleType);
      /**
       * 加载数据表格配置页面
       */
      this.loadTableConfigComponent(tableModuleType);
    },
    /** 修改数据表格样式Demo数据 **/
    setTableDemoData(data){
      this.tableDemoData = data
    }
  },
  watch:{
    'columns':{
      immediate:true,
      deep:true,
      handler(val){
        this.assTableConfig();
      }
    },
    formBuildKey:{
      immediate:true,
      handler(val){
        /** 获取数据表配置 */
        if (this.isNotEmpty(val)) {
          this.getCrudTableConfig()
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>

  .config-divider .el-divider__text{
    font-weight: bold !important;
  }

  .columnInfo-box{
    width: 100%;
    display: flex;

    .column-table{
      //width: 70%;
    }
    .column-config{
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      align-items: flex-start;

      .title{
        width: 100%;
        text-align: center;
        font-weight: bold;
        font-size: 13px;
        height: 43px;
        line-height: 43px;
        border-bottom: 1px solid #EBEEF5;
      }

      .column-form{
        overflow-y: auto;
        padding: 20px 10px;
      }
    }
  }

  .tableInfo-box{
    display: flex;

    .table-box{
      width: 80%;
    }

    .table-style-config{
      flex: 1;

      .column-form{
        overflow-y: auto;
        padding: 20px 10px;
      }
    }

  }

  .copy-column{
    color: #337ab7;

    &:hover{
      cursor:pointer
    }

  }

</style>
